package com.jjx.service.impl;

import com.github.pagehelper.PageHelper;
import com.jjx.dao.IUserMapper;
import com.jjx.domain.*;
import com.jjx.service.IUserService;
import com.jjx.utils.MD5Utils;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements IUserService {


    @Autowired
    private IUserMapper iUserMapper;

    @Override
    public List<SysUser> findAll(Integer page, Integer limit, SysUser sysUser) {

        if (sysUser.getLogin_name()!=null && !"".equals(sysUser.getLogin_name())){
            sysUser.setLogin_name("%"+sysUser.getLogin_name()+"%");
        }

        PageHelper.startPage(page,limit);
        return iUserMapper.findAllOrByCondition(sysUser);
    }

    public SysUser findByCondition(SysUser user) {
        return iUserMapper.selectOne(user);
    }

    public Result save(SysUser user) {
        //判断该用户是否存在
        if (JudgeIsExit(user.getLogin_name(),null,null)){
            return new Result(CodeMsg.ADD_ERROR);
        }
        if (JudgeIsExit(null,user.getEmail(),null)){
            return new Result(CodeMsg.ADD_ERROR_EMAIL_EXIT);
        }
        if (JudgeIsExit(null,null,user.getMobile())){
            return new Result(CodeMsg.ADD_ERROR_PHONE_EXIT);
        }
        MD5Utils md5Utils = new MD5Utils();
        user.setPwd(md5Utils.encode(user.getPwd()));
        //都不存在
        iUserMapper.insertSelective(user);

        return new Result();
    }

    public Result update(SysUser user) {
        //先判断手机号是否重复了
        if (JudgeIsExit2(user.getId(),user.getEmail(),null)){
            return new Result(CodeMsg.UPDATE_ERROR_EMAIL_EXIT);
        }
        if (JudgeIsExit2(user.getId(),null,user.getMobile())){
            return new Result(CodeMsg.UPDATE_ERROR_PHONE_EXIT);
        }
        MD5Utils md5Utils = new MD5Utils();
        user.setPwd(md5Utils.encode(user.getPwd()));
        //修改
        iUserMapper.updateByPrimaryKeySelective(user);
        return new Result();
    }

    public void delete(int[] id) {
        for (int i : id) {
            iUserMapper.deleteByPrimaryKey(i);
        }
    }

    /**
     * 用户登陆
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = null;
        try {
            SysUser sysU = new SysUser();
            sysU.setLogin_name(username);
            sysUser = iUserMapper.findAllOrByCondition(sysU).get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("sysUser"+sysUser);
        User user = new User(sysUser.getLogin_name(),
                sysUser.getPwd(),
                sysUser.getStatus() == "0" ? false : true,
                true,
                true,
                true,
                getAuthority(sysUser.getRole())
        );
        return user;
    }

    public List<SimpleGrantedAuthority> getAuthority(Role role) {
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        if (role != null) {
            list.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
        }
        System.out.println("role"+role);
        System.out.println(list);
        return list;
    }

    /**
     * 判断用户是否存在
     * @param loginName 用户名
     * @param email 邮箱
     * @param phone 电话
     * @return
     */
    public boolean JudgeIsExit(String loginName,String email,String phone){
        SysUser user = new SysUser();
        if (loginName!=null &&!"".equals(loginName)){
            user.setLogin_name(loginName);
           return iUserMapper.selectOne(user) == null?false:true;
        }
        if (email!=null &&  !"".equals(email)){
            user.setEmail(email);
            return iUserMapper.selectOne(user) == null?false:true;
        }
        if (phone!=null &&  !"".equals(phone)){
            user.setMobile(phone);
            return iUserMapper.selectOne(user) == null?false:true;
        }
        return false;
    }

    /**
     * 判断某些字段是否存在
     * @param id 用户名
     * @param email 邮箱
     * @param phone 电话
     * @return
     */
    public boolean JudgeIsExit2(Integer id, String email, String phone){
        Example example = new Example(SysUser.class);
        Example.Criteria criteria = example.createCriteria();
        if (phone!=null&&!"".equals(phone)){
            criteria.andEqualTo("mobile",phone);
            criteria.andNotIn("id", Collections.singleton(id));
           return iUserMapper.selectCountByExample(example) == 0 ? false:true;
        }
        if (email!=null&&!"".equals(email)){
            criteria.andEqualTo("email",email);
            criteria.andNotIn("id", Collections.singleton(id));
            return iUserMapper.selectCountByExample(example) == 0 ? false:true;
        }
        return false;
    }
}
